package com.sanyou.utils;

import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

public class DateUtils {

    private final static String DEFAULT_DATEFORMAT = "yyyy-MM-dd HH:mm:ss";//默认的日期格式

    /**
     * 根据时间 和时间格式 校验是否正确
     * @param length 校验的长度
     * @param sDate 校验的日期
     * @param format 校验的格式
     * @return
     */
    public static boolean isLegalDate(int length, String sDate,String format) {
        if ((sDate == null) || (sDate.length() != length)) {
            return false;
        }
        DateFormat formatter = new SimpleDateFormat(format);
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取两段日期内的所有日期
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<LocalDate> getBetweenDate(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> list = new ArrayList<>();
        long distance = ChronoUnit.DAYS.between(startDate, endDate);
        if (distance < 1) {
            return list;
        }
        Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(list::add);
        return list;
    }


    public static Date stringToDate(String time){
        return stringToDate(time,null);

    }

    public static Date stringToDate(String time, String dateFormat){
        if (StringUtils.isEmpty(dateFormat)){
            dateFormat = DEFAULT_DATEFORMAT;
        }

        try {
            return new SimpleDateFormat(dateFormat).parse(time);
        } catch (ParseException e) {
            return null;
        }

    }
}
